﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_QuanLyHoSoChamDut_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            BindToGrid()
            btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
        End If
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1 _
          , Optional ByVal intCertifiedID As Integer = -1 _
          , Optional ByVal strCertifiedCode As String = "" _
          , Optional ByVal strNguoitao As String = "" _
          , Optional ByVal dtmNgayTaoFrom As Date = #1/1/1900# _
          , Optional ByVal dtmNgayTaoTo As Date = #12/31/3999# _
          , Optional ByVal strNguoiSua As String = "" _
          , Optional ByVal dtmNgaySuaFrom As Date = #1/1/1900# _
          , Optional ByVal dtmNgaySuaTo As Date = #12/31/3999# _
          , Optional ByVal intStatusId As Integer = -1 _
          , Optional ByVal dtmNgayChamDutFrom As Date = #1/1/1900# _
          , Optional ByVal dtmNgayChamDutTo As Date = #12/31/3999# _
          , Optional ByVal strGhiChu As String = "" _
          , Optional ByVal intHuyenId As Integer = -1 _
      )

        Using data As New VSEntities
            Dim arrSearch() As String = {iPage.ToString, intCertifiedID.ToString, strCertifiedCode.ToString, strNguoitao.ToString, dtmNgayTaoFrom.ToString, dtmNgayTaoTo.ToString, strNguoiSua.ToString, dtmNgaySuaFrom.ToString, dtmNgaySuaTo.ToString, intStatusId.ToString, dtmNgayChamDutFrom.ToString, dtmNgayChamDutTo.ToString, strGhiChu.ToString, intHuyenId.ToString}
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            intHuyenId = Session("HuyenId")
            Dim p As List(Of uspCertifiedChamDutSelectAll_Result)
            p = data.uspCertifiedChamDutSelectAll(intCertifiedID _
                , strCertifiedCode _
                , strNguoitao _
                , dtmNgayTaoFrom _
                , dtmNgayTaoTo _
                , strNguoiSua _
                , dtmNgaySuaFrom _
                , dtmNgaySuaTo _
                , intStatusId _
                , dtmNgayChamDutFrom _
                , dtmNgayChamDutTo _
                , strGhiChu _
                , intHuyenId _
            , iPage, intPag_Size).ToList


            intStatusId = TinhTrangHoSo.ChoDuyet 'Tình trang hồ sơ đang chờ duyệt
            Dim intStatusId_DD = TinhTrangHoSo.Daduyet 'Tình trang hồ sơ đã tiếp nhận tckh
            p = (From i In p Where i.StatusId = intStatusId Or i.StatusId = intStatusId_DD And i.HuyenId = intHuyenId Select i).ToList()

            Dim strKey_Name() As String = {"Id", "CertifiedID", "CertifiedCode", "StatusId"}
            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault.Total()
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            If (hidCount.Value > 0) Then
                lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            Else
                lblTotal.Text = ""
            End If
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip) _
       , arrSearch(1) _
       , arrSearch(2) _
       , arrSearch(3) _
       , arrSearch(4) _
       , arrSearch(5) _
       , arrSearch(6) _
       , arrSearch(7) _
       , arrSearch(8) _
       , arrSearch(9) _
       , arrSearch(10) _
        )
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("Id").ToString
            Dim q = (From p In data.CertifiedChamDuts Where p.Id = intId Select p).FirstOrDefault
            Dim _certifiedCode As String = q.CertifiedCode
            Dim _HuyenId As Integer = Session("HuyenId")
            Try
                data.CertifiedChamDuts.DeleteObject(q)
                Insert_App_Log("Xóa  CertifiedChamDut:" & q.CertifiedCode & " ID " & q.CertifiedID & "", Function_Name.CertifiedChamDut, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                data.uspCertifiedChamDutUpdate(_certifiedCode, _HuyenId, 0)
                data.SaveChanges()
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        intTotal += 1
                        intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                        Dim q = (From p In data.CertifiedChamDuts Where p.Id = intId Select p).FirstOrDefault
                        Dim _certifiedCode As String = q.CertifiedCode
                        Dim _HuyenId As Integer = Session("HuyenId")
                        Try
                            data.CertifiedChamDuts.DeleteObject(q)
                            data.uspCertifiedChamDutUpdate(_certifiedCode, _HuyenId, 0)
                            Insert_App_Log("Xóa  CertifiedChamDut:" & q.CertifiedCode & " ID " & q.CertifiedID & "", Function_Name.CertifiedChamDut, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                            data.SaveChanges()
                            intCount += 1
                        Catch ex As Exception
                        End Try
                    End If
                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Using _data As New VSEntities
                Dim status As Integer = grdShow.DataKeys(e.Row.RowIndex)("StatusId")
                Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
                lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1

                Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
                Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
                ScriptManager.RegisterAsyncPostBackControl(lnkbtnDelete)
                Dim chkItem As CheckBox = CType(e.Row.FindControl("chkItem"), CheckBox)
                'Permission
                If HasPermission(Function_Name.CertifiedHousehold, Session("RoleID"), status, Audit_Type.Delete) = True Then
                    lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
                Else
                    lnkbtnDelete.Enabled = False
                    chkItem.Enabled = False
                End If

                Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
                'Permission
                hplEdit.Enabled = HasPermission(Function_Name.CertifiedHousehold, Session("RoleID"), status, Audit_Type.Edit)
                hplEdit.NavigateUrl = "../../Page/QuanLyHoSoChamDut/Edit.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString & "&CertifiedID=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
                Dim hplCertifiedCode As HyperLink = CType(e.Row.FindControl("hplCertifiedCode"), HyperLink)
                hplCertifiedCode.NavigateUrl = "../../Page/QuanLyHoSoChamDut/Detail.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString & "&CertifiedID=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
                hplCertifiedCode.Text = grdShow.DataKeys(e.Row.RowIndex)("CertifiedCode").ToString
                'load tinh trang ho so

                Dim _statusId As Integer = grdShow.DataKeys(e.Row.RowIndex)("StatusId").ToString
                Dim st = (From q In _data.Status Where q.StatusId = _statusId Select q).FirstOrDefault
                If Not st Is Nothing Then
                    Dim lblStatusId As Label = CType(e.Row.FindControl("lblStatusId"), Label)
                    lblStatusId.Text = st.TitleHoSo

                End If
                Dim _CertifiedID As Integer = grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
                Dim _p = (From q In _data.CertifiedHouseholds Where q.CertifiedID = _CertifiedID Select q).FirstOrDefault
                If Not _p Is Nothing Then
                    Dim hplBiz_VietName As HyperLink = CType(e.Row.FindControl("hplBiz_VietName"), HyperLink)
                    hplBiz_VietName.NavigateUrl = "../../Page/QuanLyHoSoChamDut/Detail.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString & "&CertifiedID=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
                    hplBiz_VietName.Text = IIf(IsNothing(_p.Biz_VietName), "", _p.Biz_VietName)

                    Dim lblOw_Name As Label = CType(e.Row.FindControl("lblOw_Name"), Label)
                    lblOw_Name.Text = IIf(IsNothing(_p.Ow_Name), "", _p.Ow_Name)
                End If
            End Using
        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindToGrid(1 _
      , -1 _
      , txtCertifiedcode.Text.Trim _
      , txtNguoitao.Text.Trim _
      , StringToDate(txtNgaytaoFrom.Text.Trim, "dd/mm/yyyy") _
      , StringToDate(IIf(String.IsNullOrEmpty(txtNgaytaoTo.Text.Trim) = True, "31/12/3999", txtNgaytaoTo.Text.Trim), "dd/mm/yyyy") _
      , txtNguoisua.Text.Trim _
      , StringToDate(txtNgaysuaFrom.Text.Trim, "dd/mm/yyyy") _
      , StringToDate(IIf(String.IsNullOrEmpty(txtNgaysuaTo.Text.Trim) = True, "31/12/3999", txtNgaysuaTo.Text.Trim), "dd/mm/yyyy") _
      , CInt(IIf(String.IsNullOrEmpty(txtStatusid.Text) = True, -1, txtStatusid.Text)) _
      , StringToDate(txtNgaychamdutFrom.Text.Trim, "dd/mm/yyyy") _
      , StringToDate(IIf(String.IsNullOrEmpty(txtNgaychamdutTo.Text.Trim) = True, "31/12/3999", txtNgaychamdutTo.Text.Trim), "dd/mm/yyyy") _
      , "" _
      , Session("HuyenId") _
            )
    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1) _
        , arrSearch(2) _
        , arrSearch(3) _
        , arrSearch(4) _
        , arrSearch(5) _
        , arrSearch(6) _
        , arrSearch(7) _
        , arrSearch(8) _
        , arrSearch(9) _
        , arrSearch(10) _
        , arrSearch(11) _
        , arrSearch(12) _
        , arrSearch(13) _
         )
    End Sub
    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
        txtCertifiedcode.Text = ""
        txtNguoitao.Text = ""
        txtNgaytaoFrom.Text = ""
        txtNgaytaoTo.Text = ""
        txtNguoisua.Text = ""
        txtStatusid.Text = ""
        drpPage_Size.SelectedIndex = -1
        BindToGrid(1)
    End Sub
#End Region
End Class
